/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * vec.cpp
 * Copyright (C) 罗大元 2010 <luodayuan2@gmail.com>
 * 
 */

#ifndef _VEC_H_
#define _VEC_H_

#include<algorithm>
#include<memory>
#include<cstddef>

template<class T>
class vec
{
    public:
        typedef T* iterator;
        typedef const T* const_iterator;
        typedef std::size_t size_type;
        typedef T value_type;
        typedef T& reference;
        typedef const T& const_reference;

        vec()
        {
            create();
        }

        explicit vec(size_type n,const_reference t = T())
        {
            create(n,t);
        }

        //复制构造函数
        vec(const_reference v)
        {
            create(v.begin(),v.end());
        }

        //赋值操作符
        vec& operator = (const vec&);

        //析构函数
        ~vec()
        {
            uncreate();
        }

        //索引操作符重载
        reference operator[] (size_type i)
        {
            return data[i];
        }

        const_reference operator[](size_type i)const
        {
            return data[i];
        }


        //push_back函数
        void push_back(const_reference t)
        {
            if(avail ==limit)
                grow();
            unchecked_append(t);
        }

        size_type size()const
        {
            return avail - data;
        }

        iterator begin()
        {
            return data;
        }

        const_iterator begin()const
        {
            return data;
        }


        iterator end()
        {
            return avail;
        }

        const_iterator end()const
        {
            return avail;
        }


    private:
        iterator data;
        iterator avail;
        iterator limit;


        std::allocator<T> alloc;
        void create();
        void create(size_type,const_reference);
        void create(const_iterator,const_iterator);
        void uncreate();
        void grow();
        void unchecked_append(const_reference);

};

#endif // _VEC_H_
